<?php
namespace app\admin\model;

use think\Db;
use think\facade\Config;
use think\Model;

class BusDiversionWord extends Model
{
	//一对多关联
	public function busDiversionConfig()
    {
        return $this->hasMany('BusDiversionConfig','diversion_id');
    }

    public static function getKeyWordInfo()
    {
        return self::with('busDiversionConfig')->select();
    }

    /**
     * [getKeyWordMessage 关键字列表]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public static function getKeyWordMessage($request)
    {
    	$where = [];
    	if ($request['cid'] != '') {
    		$where[] = ['cid','=',$request['cid']];
    	}
    	return self::alias('w')
    				->field('w.*,c.company_name,count(diversion_id) as config_number')
    				->where($where)
    				->join('bus_channel c','c.channel_id = w.cid', 'LEFT')
                    ->join('bus_diversion_config dc', 'dc.diversion_id = w.id', 'LEFT')
                    ->group('dc.diversion_id')
    				->paginate($request['limit'], false, $request)
    				->each(function ($item, $key) {
		                $item->company_name = $item->company_name . '/' . $item->cid;
		                switch ($item->onoff) {
		                    case '1':
		                        $item->onoff_ = '<span class="layui-badge layui-bg-green status-qy">开启</span>';
		                        break;

		                    default:
		                        $item->onoff_ = '<span class="layui-badge status-jy">禁用</span>';
		                        break;
		                }
                        $item->view_config = '<a href="javascript:;" style="color:blue" onClick="addConfig(' . $item->id . ')">添加配置('. $item->config_number .')</a>';
		            })
		            ->toArray();
	}

    public static function add($request)
    {
        //查询渠道是否已有一个开启
        $wordInfo = self::where('cid',$request['cid'])->where('onoff',1)->find();
        if ($wordInfo && $request['onoff'] == 1) {
            //一个渠道只能开启一个
            $request['onoff'] = 0;
        }
        try {
            $request['create_time'] = date('Y-m-d H:i:s');
            $request['update_time'] = date('Y-m-d H:i:s');
            self::create($request);
            deleteCache();
            return json(['code' => 200 ,'msg' => '添加成功']);
        } catch (\Exception $e) {
            trace('添加分流关键字失败--' . $e->getMessage());
            return json(['code' => 422, 'msg' => '添加失败']);
        }
    }

    public static function upd($request)
    {
        $wordInfo = self::where('cid',$request['cid'])->where('onoff',1)->find();
        if ($request['onoff'] == '1' && $wordInfo) {
            return json(['code' => 422, 'msg' => '该渠道已有开启的关键字分流']);
        } else {
            try {
                $id = $request['id'];
                unset($request['id']);
                $request['update_time'] = date('Y-m-d H:i:s');
                self::where(['id' => $id])->update($request);
                deleteCache();
                return json(['code' => 200, 'msg' => '更新成功']);
            } catch (\Exception $e) {
                trace('更新关键字分流失败--' . $e->getMessage());
                return json(['code' => 422 ,'msg' => '更新失败']);
            }
        }

    }

    public static function onoff($request)
    {
        $wordInfo = self::where('cid',$request['cid'])->where('onoff',1)->where('id','neq',$request['id'])->find();
        if ($request['status'] == '1' && $wordInfo) {
            return json(['code' => 422, 'msg' => '该渠道已有开启的关键字分流']);
        } else {
            trace(session('username') . '把关键字分流id:' . $request['id'] . '的开启状态改为了' . $request['status'], 'info');
            try {
                self::where(['id' => $request['id']])->update(['onoff' => $request['status']]);
                deleteCache();
                return json(['code' => 200, 'msg' => '更新成功']);
            } catch (\Exception $e) {
                trace('开启关键字分流失败--' . $e->getMessage());
                return json(['code' => 422 ,'msg' => '更新失败']);
            }
        }
    }

}
